import store from "../store";
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";

Vue.use(VueRouter);

// 重写路由的push与replace方法
const originPush = VueRouter.prototype.push
const originreplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location,okCallBack,errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originPush.call(this, location).catch(() => { })
  } else {
    originPush.call(this,location,okCallBack,errCallBack)
  }
}

VueRouter.prototype.replace = function (location,okCallBack,errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originreplace.call(this, location).catch(() => { })
  } else {
    originreplace.call(this,location,okCallBack,errCallBack)
  }
}




//设置路由信息
const router = new VueRouter({
  mode:'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return{x:0,y:0}
    }
  }
});

const whiteList = [
  "home",
  "login",
  "register",
  "search",
  "detail",
  "addcartsuccess",
  "shopcart",
];
router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.name) || store.state.user.userInfo.token) {
    next();
    return;
  }
  // console.log(to, from);
  next({
    name: "login",
    query: {
      redirect: to.path,
    },
  });
});
export default router